package com.qfedu.utils;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author han tao
 * @version 1.0
 * @date 2023/3/30 14:18
 * @project day26-jdbc
 */
public class DruidUtil {
    private static DataSource dataSource ;

    // 为了初始化连接池
    static {
        try {
            Properties properties = new Properties();
            InputStream resourceAsStream = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            // 加载配置文件
            properties.load(resourceAsStream);
            // 通过静态工厂方法完成初始化
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    // 获取连接池
    public static DataSource getDataSource(){
        return dataSource;
    }
}
